<template>
	<div>
		<cc-table-modify
			title="设施列表"
			with-delete
			:items="facilities"
			:default-item="{ title: ''}"
			@add="handleAddFacility"
			@change="handleFacilitiesChange"
		>
			<template>
				<el-table-column prop="title" label="标题">
					<template v-slot="scope">
						<el-input
							v-model="scope.row.title"
							@focus="facility = Object.assign({}, scope.row)"
							@blur="handleFacilityBlur(scope.row)"
						/>
					</template>
				</el-table-column>
			</template>
		</cc-table-modify>
	</div>
</template>

<script>
	import ccTableModify from "@/components/cc-table-modify";

	export default {
		components: {
			"cc-table-modify": ccTableModify
		},
		data() {
			return {
				facilities: [],
				facility: {}
			};
		},
		mounted() {
			this.getFacilities();
		},
		methods: {
			async getFacilities() {
				this.facilities = await this.$http.get("/facilities");
			},

			async handleAddFacility() {
				const res = await this.$http.post("/facilities", undefined, true);
				if (!res) return;
				this.facilities.unshift(res);
			},

			async handleFacilitiesChange(items, dItems) {
				const res = await this.$http.delete(
					`/facilities/${dItems.map(i => i._id).join("-")}`,
					undefined,
					true
				);
				res && (this.facilities = items);
			},

			async handleFacilityBlur(item) {
				if (this.facility.title === item.title) return;
				const res = await this.$http.put(
					`/facilities/${item._id}`,
					item,
					true
				);
				if (!res) {
					item.title = this.facility.title;
					this.facility = {};
				}
			}
		}
	};
</script>

<style lang="less" scoped>
</style>
